package com.sniper.springmvc.mybatis.service.impl;

import com.sniper.springmvc.model.AdminGroup;
import com.sniper.springmvc.model.AdminGroupRight;
import com.sniper.springmvc.model.AdminRight;
import com.sniper.springmvc.mybatis.dao.BaseDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("adminGroupService")
public class AdminGroupServiceImpl extends BaseServiceImpl<AdminGroup>
        implements AdminGroupService {

    @Resource
    private AdminGroupRightService adminGroupRightService;

    @Override
    @Resource(name = "adminGroupDao")
    public void setDao(BaseDao<AdminGroup> dao) {
        super.setDao(dao);
    }

    @Override
    public int insert(AdminGroup t) {
        int result = super.insert(t);
        save(t);
        return result;
    }

    private void save(AdminGroup t) {
        List<AdminRight> adminRights = t.getAdminRight();
        for (AdminRight adminRight : adminRights) {
            AdminGroupRight adminGroupRight = new AdminGroupRight();
            adminGroupRight.setGroup_id(t.getId());
            adminGroupRight.setRight_id(adminRight.getId());
            adminGroupRightService.insert(adminGroupRight);
        }
    }

    /**
     * 重写方法更新关联关系
     */
    @Override
    public int update(AdminGroup t) {

        if (t.getAdminRight().size() > 0) {
            // 删除
            adminGroupRightService.delete(t.getId());
            // 新增
            save(t);
        }
        return super.update(t);
    }

    @Override
    public int delete(String id) {
        adminGroupRightService.delete(id);
        return super.delete(id);
    }


    @Override
    public AdminGroup getGroup(String value) {
        Map<String, Object> params = new HashMap<>();
        params.put("value", value);
        return (AdminGroup) this.find("find", params);
    }
}
